package com.tsd.core.utils;

import com.tsd.core.datasource.SpringContextUtil;
import com.tsd.core.vo.HlpException;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * @ClassName: RefectUtil
 * @Description: 反射调用工具类
 * @Author: Hillpool
 * @Date: 2022/8/17 14:32
 * @Version: 1.0
 */
public class RefectUtil {

    /**
     * spring调用方法
     *
     * @param serviceName 服务名称
     * @param methodName  方法名称
     * @param params      参数
     * @return
     * @throws Exception
     */
    public static Object springInvokeMethod(String serviceName, String methodName, Object[] params) throws Exception {
        Object service = SpringContextUtil.getBean(serviceName);
        if (HlpUtils.isEmpty(service)) {
            throw new HlpException(String.format("Spring上下文中未找到对象[%s]", serviceName));
        }
        Class<?>[] paramClass = null;
        if (params != null) {
            int paramsLength = params.length;
            paramClass = new Class[paramsLength];
            for (int i = 0; i < paramsLength; i++) {
                paramClass[i] = params[i].getClass();
            }
        }
        // 找到方法
        Method method = ReflectionUtils.findMethod(service.getClass(), methodName, paramClass);
        // 执行方法
        if (HlpUtils.isEmpty(method)) {
            throw new HlpException(String.format("方法不存在：%s.%s", serviceName, methodName));
        }
        return ReflectionUtils.invokeMethod(method, service, params);
    }
}
